/**
 * Module dependencies
 */
var express = require('express'),
    namespace = require('express-namespace'),
	bodyparser = require('body-parser');
// var getDataFromOuter = require('./lib/getDataFromOuter');
var weixinauthdata = require('./lib/weixinauthdata.js');
var OAuth = require('wechat-oauth');
var client = new OAuth('wx8cec766c8474008e', '78af118201c9a749292b5acb084756e1');
var domain = 'http://qbrp3.free.natapp.cc';

//create an express app
var app = express();


//socket.io 操作
var server = require('http').createServer(app);
var io = require('socket.io')(server);
// require('./lib/maxpupSocket.js').setIO(io);


app.set('port', process.env.PORT || 3000);

//视图设置
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

// log all requests
app.all('*', function(req, res, next) {
    console.log("maxpup Received request to " + req.url);
    next();
});

//设置静态文件夹
app.use('',express.static('public'));

//访问温度控制界面
app.get('/tc',function(req,res){
    res.redirect('/index.html');
});

//访问下载app页面
app.get('/download',function(req,res){
    res.redirect('/appdownload.html');
});

// //连接socket服务器
// app.get('/connect', function(req,res) {
//    var client = require('./lib/getDataFromOuter.js');
//    client.connectToRemort();
// })
/**
 * 微信认证
 * signature
 * openid
 * check
 */
app.get('/redictTotc',function(req,res){
  var url = client.getAuthorizeURL(domain + '/callback', '','snsapi_base');
  console.log(url);
  res.redirect(url)
});

app.get('/check',function(req,res){
  var signature = req.query.signature;
  var timestamp = req.query.timestamp;
  var echoStr = req.query.echostr;
  console.log("签名："+ signature + "时间戳：" + timestamp);
  res.send(echoStr);
});

//扫描二维码
app.get('/scanQRCode',function(req,res){
  express.static('public');
  var promise = weixinauthdata.getSignature();
  promise.then(function(ret) {
    console.log('signature : ' + ret.signature);
    res.render('scanQRCode', { ret: ret });
  });
});

//TODO 微信回调函数
app.get('/callback', function(req, res) {
  console.log('----weixin callback -----')
  var code = req.query.code;
  client.getAccessToken(code, function (err, result) {
    console.dir(err)
    console.dir(result)
    if (err === null) {
      var accessToken = result.data.access_token;
      var openid = result.data.openid;

      console.log('token=' + accessToken);
      console.log('openid=' + openid);
    }


    });
});

//监听
// app.listen(app.get('port'), function() {
//   console.log('Express server listening on port ' + app.get('port'));
// });
server.listen(app.get('port'), function () {
  console.log('Server listening at port %d', app.get('port'));
});
